package cz.kfad.ofrss.common;

import android.app.Activity;
import android.app.Application;
import android.widget.Toast;
import cz.kfad.ofrss.model.Category;
import cz.kfad.ofrss.model.Channel;

public class ApplicationContext extends Application {
	private AsynRefresh asynRefresh;
	private AsynCategory asynCategory;
	private AsynChannel asynChanel;

	public ApplicationContext() {
		asynRefresh = new AsynRefresh();
	}


	public void executeAsynRefreshTask(Activity context, DoneCallback done) {

		if (!NetworkHelper.isNetworkConnected(context)) {
			Toast.makeText(context, "No network connection", Toast.LENGTH_SHORT).show();
			return;
		}
		if (!asynRefresh.isStarted()) {
			asynRefresh.execute();
			return;
		}
		if (!asynRefresh.isEnded()) {
			Toast.makeText(context, "already fetching", Toast.LENGTH_SHORT).show();
			return;
		}

		asynRefresh = new AsynRefresh(context, done);
		asynRefresh.execute();
	}

	public void setContextToAsynTasks(Activity context) {
		setContextToAsynTasks(context, null);
	}

	public void setContextToAsynTasks(Activity context, DoneCallback afterRefresh) {
		asynRefresh.setContext(context);
		asynRefresh.setDone(afterRefresh);
		if (asynCategory != null) {
			asynCategory.setContext(context);
		}
		if (asynChanel != null) {
			asynChanel.setContext(context);
		}
		
	}

	public void saveOrUpdate(Category category, Activity context) {
		AsynCategory asynCreateCategory = new AsynCategory();
		asynCreateCategory.setContext(context);
		asynCreateCategory.execute(category);
		asynCategory = asynCreateCategory;
	}

	public void saveOrUpdate(Channel channel, Activity context) {
		AsynChannel asynChannel = new AsynChannel();
		asynChannel.setContext(context);
		asynChannel.execute(channel);
		this.asynChanel = asynChannel;
	}
}
